<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!-- 工序数据 -->
      <el-col :span="3" :xs="24">
        <!-- <el-input v-model="processName" placeholder="请输入工序名称" clearable size="small" prefix-icon="el-icon-search"
          style="margin-bottom: 20px" /> -->
        <el-tree ref="tree" node-key="id" highlight-current :data="processDate" :props="defaultProps" @node-click="lineClick" />
      </el-col>
      <el-col :span="21" :xs="24">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
          label-width="100px">
          <!-- <el-form-item label="部门ID" prop="deptId">
        <el-input
          v-model="queryParams.deptId"
          placeholder="请输入部门ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
          <!-- <el-form-item label="工序ID" prop="processId">
        <el-input
          v-model="queryParams.processId"
          placeholder="请输入工序ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
          <!-- <el-form-item label="产品ID" prop="productId">
        <el-input
          v-model="queryParams.productId"
          placeholder="请输入产品ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
          <el-form-item label="产品" prop="productId">
            <el-select v-model="queryParams.productId" placeholder="请选择产品" clearable >
            <el-option v-for="item in productList" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
          </el-form-item>
      <el-form-item label="工种类型" prop="workerType">
        <el-select v-model="queryParams.workerType" placeholder="请选择工种类型" clearable>
          <el-option v-for="dict in workerTypes" :key="dict.dictValue" :label="dict.dictLabel"
            :value="dict.dictValue" />
        </el-select>
      </el-form-item>
          <el-form-item label="预警时间" prop="warningTime">
            <el-input v-model="queryParams.warningTime" placeholder="请输入预警时间" clearable
              @keyup.enter.native="handleQuery" />
          </el-form-item>
          <el-form-item label="拉动时间" prop="pullTime">
            <el-input v-model="queryParams.pullTime" placeholder="请输入拉动时间" clearable
              @keyup.enter.native="handleQuery" />
          </el-form-item>
          <!-- <el-form-item label="单人缩短工时" prop="oneManReduction">
            <el-input v-model="queryParams.oneManReduction" placeholder="请输入单人缩短工时" clearable
              @keyup.enter.native="handleQuery" />
          </el-form-item>
          <el-form-item label="消耗工作效率" prop="consumedWorkEfficiency">
            <el-input v-model="queryParams.consumedWorkEfficiency" placeholder="请输入消耗工作效率" clearable
              @keyup.enter.native="handleQuery" />
          </el-form-item>
          <el-form-item label="效率类型" prop="efficiencyType">
          <el-select v-model="queryParams.efficiencyType" placeholder="请选择效率类型" clearable>
            <el-option v-for="dict in efficiencyTypes" :key="dict.dictValue" :label="dict.dictLabel"
              :value="dict.dictValue" />
          </el-select>
        </el-form-item> -->
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
              v-hasPermi="['zndd:processset:add']" v-if="this.currentProcessList.length > 0 || this.currentProcessId != null">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
              v-hasPermi="['zndd:processset:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
              v-hasPermi="['zndd:processset:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
              v-hasPermi="['zndd:processset:export']">导出</el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="processsetList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column type="index" label="序号" />
          <!-- <el-table-column label="主键" align="center" prop="id" /> -->
          <!-- <el-table-column label="部门ID" align="center" prop="deptId" /> -->
          <!-- <el-table-column label="工序ID" align="center" prop="processId" /> -->
          <!-- <el-table-column label="产品ID" align="center" prop="productId" /> -->
          <el-table-column label="产品" align="center" prop="productId" :formatter="productFormatter"/>
          <el-table-column label="预警时间（秒）"  width="140" align="center" prop="warningTime" />
          <el-table-column label="拉动时间（秒）"  width="140" align="center" prop="pullTime" />
          <el-table-column label="工种" align="center" prop="workerType"  :formatter="workerTypeFomatter"/>
          <!-- <el-table-column label="单人缩短工时（秒）" width="150" align="center" prop="oneManReduction" />
          <el-table-column label="消耗工作效率（%）" width="140" align="center" prop="consumedWorkEfficiency" />
          <el-table-column label="效率类型" align="center" prop="efficiencyType" :formatter="efficiencyTypeFomatter"/> -->
          <el-table-column label="备注" align="center" prop="remark" />
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                v-hasPermi="['zndd:processset:edit']">修改</el-button>
              <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                v-hasPermi="['zndd:processset:remove']">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize" @pagination="getList" />
      </el-col>
    </el-row>
    <!-- 添加或修改工序配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="170px">
        <!-- <el-form-item label="部门ID" prop="deptId">
          <el-input v-model="form.deptId" placeholder="请输入部门ID" />
        </el-form-item>
        <el-form-item label="工序ID" prop="processId">
          <el-input v-model="form.processId" placeholder="请输入工序ID" />
        </el-form-item>
        <el-form-item label="产品ID" prop="productId">
          <el-input v-model="form.productId" placeholder="请输入产品ID" />
        </el-form-item> -->
        <el-form-item label="工序" prop="processId" v-if="this.currentProcessList.length > 0 && this.currentProcessId == null">
          <el-select v-model="form.processId" placeholder="请选择工序">
            <el-option v-for="item in currentProcessList" :key="item.id" :label="item.label" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="产品" prop="productId">
          <el-select v-model="form.productId" placeholder="请选择产品">
            <el-option v-for="item in productList" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="工种类型" prop="workerType">
          <el-select v-model="form.workerType" placeholder="请选择工种类型">
            <el-option v-for="dict in workerTypes" :key="dict.dictValue" :label="dict.dictLabel"
              :value="dict.dictValue" />
          </el-select>
        </el-form-item>
        <el-form-item label="预警时间（秒）" prop="warningTime">
          <el-input v-model="form.warningTime" placeholder="请输入预警时间" />
        </el-form-item>
        <el-form-item label="拉动时间（秒）" prop="pullTime">
          <el-input v-model="form.pullTime" placeholder="请输入拉动时间" />
        </el-form-item>
        <!-- <el-form-item label="单人缩短工时（秒）" prop="oneManReduction">
          <el-input v-model="form.oneManReduction" placeholder="请输入单人缩短工时" />
        </el-form-item>
        <el-form-item label="消耗工作效率（%）" prop="consumedWorkEfficiency">
          <el-input v-model="form.consumedWorkEfficiency" placeholder="请输入消耗工作效率" />
        </el-form-item>
        <el-form-item label="效率类型" prop="efficiencyType">
          <el-select v-model="form.efficiencyType" placeholder="请选择效率类型">
            <el-option v-for="dict in efficiencyTypes" :key="dict.dictValue" :label="dict.dictLabel"
              :value="dict.dictValue" />
          </el-select>
        </el-form-item> -->
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listProcessset, getProcessset, delProcessset, addProcessset, updateProcessset,listProcessSetQuery } from "@/api/zndd/process/processset";
import { listAllprocess } from "@/api/zndd/process/process";
import { listAllSet } from "@/api/zndd/line/set";
import { listAllDetails } from "@/api/zndd/line/details";
import { getDicts } from "@/api/system/dict/data";
import { listProducttype} from "@/api/zndd/product/producttype";

export default {
  name: "Processset",
  data() {
    return {
      //产品数组
      productList:[],
      //工序名称搜索
      processName: null,
      //当前工序名称
      currentProcessId: null,
      //当前工序数组信息
      currentProcessList: [],
      //树型工序列表
      processDate: [],
      //二级产线全部数据
      detailsList:[],
      //三级产线全部数据
      lineSetList:[],
      //工序全部数据
      processList:[],
      //工序默认查询条件
      processParams: {
        pageNum: 1,
        pageSize: 50,
        deptId: null,
        sonLineName: null
      },
      //字典表获取工种列表
      workerTypes:[],
      //字典表获取效率列表
      efficiencyTypes:[],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 工序配置表格数据
      processsetList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deptId: null,
        processId: null,
        productId: null,
        warningTime: null,
        pullTime: null,
        workerType: null,
        oneManReduction: null,
        consumedWorkEfficiency: null,
        efficiencyType: null,
        processIds:[],
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        processId: { required: true, message: '请选择工序', trigger: 'blur' },
        productId: { required: true, message: '请选择产品', trigger: 'blur' },
        workerType: [
          { required: true, message: "工种不能为空", trigger: "blur" }
        ],
        efficiencyType: [
          { required: true, message: "效率类型不能为空", trigger: "blur" }
        ],
      }
    };
  },
  watch: {
    // 根据名称筛选产线
    processName(val) {
      this.lineParams.sonLineName = val;
      this.getLineList();
    }
  },
  created() {
    //获取字典表中工种类型
    this.getDicts("zndd_job_type").then(response => {
      this.workerTypes = response.data;
    });
    //获取字典表中效率类型
    this.getDicts("zndd_process_type").then(response => {
      this.efficiencyTypes = response.data;
    });
    //获取产品数组
    listProducttype().then(response => {
      var list = [];
        response.rows.forEach(row => {
          list.push({
            label: row.productTypeName,
            value: row.id
          })
        });
        this.productList = list;
    });
    this.getLineDetalisList();
    // this.getList();
  },
  methods: {
    //产品列表格式化
    productFormatter(row, column){
      var lt = null;
      this.productList.forEach(product => {
        if (product.value == row.productId) {
          lt = product;
        }
      });
      if(lt == null){
        return "";
      }else{
        return lt.label;
      }
    },
    //格式化效率类型
    efficiencyTypeFomatter(row, column) {
      var et = null;
      this.efficiencyTypes.forEach(efficiencyType => {
        if (efficiencyType.dictValue == row.efficiencyType) {
          et = efficiencyType;
        }
      });
      if(et == null){
        return "";
      }else{
        return et.dictLabel;
      }
    },
    //格式化工种类型
    workerTypeFomatter(row, column) {
      var wt = null;
      this.workerTypes.forEach(workerType => {
        if (workerType.dictValue == row.workerType) {
          wt = workerType;
        }
      });
      if(wt == null){
        return "";
      }else{
        return wt.dictLabel;
      }
    },
    //树型工序点击事件
    lineClick(data) {
      this.queryParams.processId = null;
      this.queryParams.processIds = [];
      this.currentProcessList = [];
      this.currentProcessId = null;
      if(data.children != undefined && data.children.length > 0){
        var processIds = [];
        var process = [];
        data.children.forEach(row => {
          if(row.children != undefined && row.children.length > 0){
            row.children.forEach(children => {
              if(children.id != undefined){
                processIds.push(children.id);
                process.push(children);
              }
            });
          }else{
            if(row.id != undefined){
              processIds.push(row.id);
              process.push(row);
            }
          }
        });
        if(processIds.length != 0){
          this.queryParams.processIds = processIds;
          this.currentProcessList = process;
        }
      }else{
        this.queryParams.processId = data.id;
        this.currentProcessId = data.id;
      }
      if(this.queryParams.processId == null && this.queryParams.processIds.length == 0){
        this.processsetList = [];
        this.loading = false;
      }else{
        this.getList();
      }
    },
    //查询二级产线信息
    getLineDetalisList(){
      listAllDetails().then(response => {
        this.detailsList = response.rows;
        this.getLineSetList();
      });
    },
    //查询三级产线信息
    getLineSetList(){
      listAllSet().then(response => {
        this.lineSetList = response.rows;
        this.getProcessList();
      });
    },
    //查询工序列表数据
    getProcessList() {
      listAllprocess().then(response => {
        this.processList = response.rows;
        var setlist = [];
        this.lineSetList.forEach(lineSet => {
          var processs = [];
          this.processList.forEach(process => {
            if(lineSet.lineNo == process.lineNo){
              processs.push({
                label: process.processName,
                id: process.id,
                value: process.lineNo
              });
            }
          });
          setlist.push({
            label:lineSet.threeLineName,
            value:lineSet.lineNo,
            lineId:lineSet.lineId,
            children:processs
          });
        });
        var list = [];
        this.detailsList.forEach(details => {
          var sets = [];
          setlist.forEach(set => {
            if(details.id == set.lineId){
              sets.push(set);
            }
          });
          list.push({
            id:details.id,
            label:details.sonLineName,
            value:details.lineNo,
            children:sets
          });
        });
        this.processDate = list;
        this.$nextTick(()=>{
          this.$refs.tree.setCurrentKey(this.processDate[0].id);
        })
        this.lineClick(this.processDate[0]);
      });
    },
    /** 查询工序配置列表 */
    getList() {
      this.loading = true;
      listProcessSetQuery(this.queryParams).then(response => {
        this.processsetList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        deptId: null,
        processId: null,
        productId: null,
        warningTime: null,
        pullTime: null,
        workerType: null,
        oneManReduction: null,
        consumedWorkEfficiency: null,
        efficiencyType: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加工序配置";
      this.form.processId = this.currentProcessId;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getProcessset(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改工序配置";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateProcessset(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addProcessset(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除选择的工序配置信息？').then(function () {
        return delProcessset(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('zndd/processset/export', {
        ...this.queryParams
      }, `工序配置_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style lang="css" scoped>
::v-deep .el-tree-node__content:hover{
  background-color: #409EFF;
  color: #ffffff;
}
::v-deep .el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content{
  background-color: #409EFF;
  color: #ffffff;
}
</style>